package org.yeyu.model;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV导出工具类
 */
public class CsvExporter {
    private static final Logger logger = LogManager.getLogger(CsvExporter.class);

    /**
     * 将搜索结果导出为CSV文件
     * @param results 搜索结果列表
     * @param file 目标文件
     * @throws IOException 如果写入文件时发生错误
     */
    public static void exportToCsv(List<SearchResult> results, File file) throws IOException {
        if (results == null || results.isEmpty()) {
            throw new IllegalArgumentException("搜索结果列表不能为空");
        }

        // 确保目录存在
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            boolean created = parentDir.mkdirs();
            if (!created) {
                throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
            }
        }

        // 创建CSV表头
        List<String> headers = new ArrayList<>();
        headers.add("工作表");
        headers.add("行号");

        // 添加实际的表头列
        if (!results.get(0).getHeaders().isEmpty()) {
            headers.addAll(results.get(0).getHeaders());
        }

        // 使用BufferedWriter和CSVPrinter来写入CSV文件
        Path filePath = Paths.get(file.toURI());

        try (BufferedWriter writer = Files.newBufferedWriter(filePath);
             CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
                     .withHeader(headers.toArray(new String[0]))
                     .withIgnoreHeaderCase()
                     .withTrim())) {

            // 写入数据行
            for (SearchResult result : results) {
                List<String> record = new ArrayList<>();
                record.add(result.getSheetName());
                record.add(String.valueOf(result.getRowNum()));

                // 添加行数据
                if (result.getRowData() != null) {
                    record.addAll(result.getRowData());
                }

                csvPrinter.printRecord(record);
            }

            // 确保所有数据都刷新到文件
            csvPrinter.flush();
            logger.info("成功导出 {} 条记录到 {}", results.size(), file.getAbsolutePath());
        } catch (IOException e) {
            logger.error("导出CSV文件失败: {}", e.getMessage(), e);
            throw new IOException("导出CSV文件失败: " + e.getMessage(), e);
        }
    }
}
